<template>
  <div class="role-container">
    <div class="search-bar">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input-search
            v-model="searchKeyword"
            placeholder="请输入角色名称"
            @search="handleSearch"
          />
        </a-col>
        <a-col :span="18" style="text-align: right">
          <a-button type="primary" @click="handleAdd">
            <template #icon><icon-plus /></template>
            新增角色
          </a-button>
        </a-col>
      </a-row>
    </div>

    <a-table
      :data="roleList"
      :loading="loading"
      :pagination="pagination"
      @page-change="onPageChange"
    >
      <template #columns>
        <a-table-column title="角色名称" data-index="roleName" />
        <a-table-column title="角色编码" data-index="roleCode" />
        <a-table-column title="描述" data-index="description" />
        <a-table-column title="排序" data-index="sort" />
        <a-table-column title="状态" data-index="status">
          <template #cell="{ record }">
            <a-switch
              :model-value="record.status === 1"
              @change="(value) => handleStatusChange(record, value)"
              :disabled="record.isSystem"
            />
          </template>
        </a-table-column>
        <a-table-column title="创建时间" data-index="createTime">
          <template #cell="{ record }">
            {{ formatDate(record.createTime) }}
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" @click="handleEdit(record)" :disabled="record.isSystem">
                编辑
              </a-button>
              <a-button type="text" @click="handlePermission(record)">
                权限
              </a-button>
              <a-popconfirm
                content="确认删除该角色吗？"
                @ok="handleDelete(record)"
                :disabled="record.isSystem"
              >
                <a-button type="text" status="danger" :disabled="record.isSystem">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 角色表单对话框 -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="formTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form :model="roleForm" ref="roleFormRef">
        <a-form-item field="roleName" label="角色名称" :rules="[{ required: true, message: '请输入角色名称' }]">
          <a-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item field="roleCode" label="角色编码" :rules="[{ required: true, message: '请输入角色编码' }]">
          <a-input v-model="roleForm.roleCode" placeholder="请输入角色编码" />
        </a-form-item>
        <a-form-item field="description" label="角色描述">
          <a-textarea v-model="roleForm.description" placeholder="请输入角色描述" />
        </a-form-item>
        <a-form-item field="sort" label="显示顺序">
          <a-input-number v-model="roleForm.sort" :min="0" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 权限分配对话框 -->
    <a-modal
      v-model:visible="permDialogVisible"
      title="分配权限"
      @ok="handlePermSubmit"
      @cancel="() => permDialogVisible = false"
    >
      <a-tree
        v-model:checked-keys="checkedMenuIds"
        :data="menuTree"
        :field-names="{ key: 'id', title: 'menuName' }"
        checkable
        :check-strictly="false"
      />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import request from '@/api/request'

// 数据列表
const roleList = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 分页配置
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true
})

// 表单相关
const dialogVisible = ref(false)
const formTitle = ref('')
const roleForm = ref({
  id: null,
  roleName: '',
  roleCode: '',
  description: '',
  sort: 0
})
const roleFormRef = ref()

// 权限相关
const permDialogVisible = ref(false)
const menuTree = ref([])
const checkedMenuIds = ref([])
const currentRole = ref(null)

// 获取角色列表
const getRoleList = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/SysRole/list', {
      params: { keyword: searchKeyword.value }
    })
    roleList.value = res.data
  } catch (error) {
    Message.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取菜单树
const getMenuTree = async () => {
  try {
    const res = await request.get('/api/SysMenu/tree')
    menuTree.value = res.data
  } catch (error) {
    Message.error('获取菜单树失败')
  }
}

// 获取角色菜单权限
const getRoleMenuIds = async (roleId) => {
  try {
    const res = await request.get(`/api/SysMenu/role/${roleId}`)
    checkedMenuIds.value = res.data
  } catch (error) {
    Message.error('获取角色权限失败')
  }
}

// 搜索
const handleSearch = () => {
  getRoleList()
}

// 新增角色
const handleAdd = () => {
  formTitle.value = '新增角色'
  roleForm.value = {
    id: null,
    roleName: '',
    roleCode: '',
    description: '',
    sort: 0
  }
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (record) => {
  formTitle.value = '编辑角色'
  roleForm.value = { ...record }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate()
    const isEdit = roleForm.value.id !== null
    const api = isEdit
      ? `/api/SysRole/${roleForm.value.id}`
      : '/api/SysRole'
    const method = isEdit ? 'put' : 'post'
    
    const res = await request[method](api, roleForm.value)
    Message.success(res.message)
    dialogVisible.value = false
    getRoleList()
  } catch (error) {
    Message.error(error.message || '操作失败')
  }
}

// 取消表单
const handleCancel = () => {
  roleFormRef.value.resetFields()
  dialogVisible.value = false
}

// 删除角色
const handleDelete = async (record) => {
  try {
    const res = await request.delete(`/api/SysRole/${record.id}`)
    Message.success(res.message)
    getRoleList()
  } catch (error) {
    Message.error('删除失败')
  }
}

// 修改状态
const handleStatusChange = async (record, value) => {
  try {
    const status = value ? 1 : 0
    const res = await request.put(`/api/SysRole/${record.id}/status/${status}`)
    Message.success(res.message)
    getRoleList()
  } catch (error) {
    Message.error('修改状态失败')
  }
}

// 分配权限
const handlePermission = async (record) => {
  currentRole.value = record
  await getMenuTree()
  await getRoleMenuIds(record.id)
  permDialogVisible.value = true
}

// 提交权限设置
const handlePermSubmit = async () => {
  try {
    const res = await request.post(
      `/api/SysRole/${currentRole.value.id}/permissions`,
      checkedMenuIds.value
    )
    Message.success(res.message)
    permDialogVisible.value = false
  } catch (error) {
    Message.error('分配权限失败')
  }
}

// 分页变化
const onPageChange = (current) => {
  pagination.value.current = current
  getRoleList()
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  getRoleList()
})
</script>

<style scoped>
.role-container {
  padding: 16px;
}

.search-bar {
  margin-bottom: 16px;
}
</style>